﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using EMANIFEST.Common;
using EMANIFEST.Common.Validation;
using EMANIFEST.Dtos;
using EMANIFEST.ImportExcelData;
using EMANIFEST.EDIFileUpload;
using EMANIFEST.eManifestService;

namespace EMANIFEST.CONTROLTEMPLATES.Emanifest_UI
{
    public partial class UploadFile : UserControl
    {
        // Delegate declaration
        public delegate void UploadFileCompleted(UploadEventArgs args);
        // Event declaration
        public event UploadFileCompleted UploadCompleted;

        //// Delegate declaration
        //public delegate void OnButtonClick(string strValue);

        //// Event declaration
        //public event OnButtonClick btnHandler;

        protected void Page_Load(object sender, EventArgs e)
        {
            //             Document.DocuementChanges.Count>0 && Document.ValidDays > 0 && Document.StatusUpdate == null OR 0

            //o   If Document.ArrivalDate >= Now è quyền sửa các form (isTemp = true)

            //o   If  Document.ArrivalDate + Document .ValidDays >= Now èquyền sửa form hàng hóa only (isTemp = true)

            //o   Update DocumentUpdate cho các trường tương ứng =1

            //o   Hiện thị Submit link if Document .ValidDays > 0 && Document.StatusUpdate == null OR 0 && Document.ArrivalDate + Document .ValidDays >= Now.

            //o   Click on Submit : Update Document.StatusUpdate = 1 if Document.ArrivalDate + Document .ValidDays >= Now.

            if (!IsPostBack)
            {
                //EmanifestServiceClient client = new EmanifestServiceClient();
                //string rid = Request.QueryString["rid"];
                //DocumentDto document = client.GetDocumentById(new Guid(rid));
            }
        }

        private string _DocumentType;
        public string DocumentType
        {
            get
            {
                return _DocumentType;
            }
            set
            {
                _DocumentType = value;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string rid = Request.QueryString["rid"];
            if (Session["DocumenType"] == null)
            {
                string msg = "Session = null [" + rid + "]";
                string prompt = "<script>$(document).ready(function(){{$.prompt('{0}!',{1});}});</script>";
                string message = string.Format(prompt, msg, "{ prefix: 'extblue' }");
                // registering the JavaScript on the page and controls with postback
                this.Page.ClientScript.RegisterStartupScript(typeof(Page), "alert", message);
                return;
            }
            DocumentType = Session["DocumenType"].ToString();
            if (string.IsNullOrEmpty(rdnStatus.SelectedValue))
            {
                lblMessage.Text = "Bạn phải chọn trạng thái";
                string msg = lblMessage.Text;
                string prompt = "<script>$(document).ready(function(){{$.prompt('{0}!',{1});}});</script>";
                string message = string.Format(prompt, msg, "{ prefix: 'extblue' }");
                // registering the JavaScript on the page and controls with postback
                this.Page.ClientScript.RegisterStartupScript(typeof(Page), "alert", message);
                return;
            }

            Guid documentId = new Guid(rid);
            if (rdnStatus.SelectedValue == "2")//xoa
            {
                #region delete
                var client = new EmanifestServiceClient();

                if (DocumentType == ((int)EnumDoucmentType.Crews).ToString())
                {
                    client.DeleteCrewByDocumentId(documentId, EMANIFEST.EmanifestUser.FBAUserId);
                }
                else if (DocumentType == ((int)EnumDoucmentType.General).ToString())
                {
                    client.DeleteGeneralDeclarationByDocumentId(documentId, EMANIFEST.EmanifestUser.FBAUserId);
                }
                else if (DocumentType == ((int)EnumDoucmentType.Good).ToString())
                {
                    client.DeleteGoodDeclarationByDocumentId(documentId, EMANIFEST.EmanifestUser.FBAUserId);
                }
                else if (DocumentType == ((int)EnumDoucmentType.GoodDangerous).ToString())
                {
                    client.DeleteDangerousGoodByDocumentId(documentId, EMANIFEST.EmanifestUser.FBAUserId);
                }
                else if (DocumentType == ((int)EnumDoucmentType.Passenger).ToString())
                {
                    client.DeletePassengerByDocumentId(documentId, EMANIFEST.EmanifestUser.FBAUserId);
                }
                else if (DocumentType == ((int)EnumDoucmentType.Stores).ToString())
                {
                    client.DeleteShipStoreDeclarationByDocumentId(documentId, EMANIFEST.EmanifestUser.FBAUserId);
                }
                else if (DocumentType == ((int)EnumDoucmentType.CrewEffect).ToString())
                {
                    client.DeleteCrewEffectDeclarationByDocumentId(documentId, EMANIFEST.EmanifestUser.FBAUserId);
                }
                if (UploadCompleted != null)
                {
                    UploadEventArgs args = new UploadEventArgs(Convert.ToInt32(DocumentType));
                    UploadCompleted(args);
                }
                #endregion
            }
            else
            {
                #region Add or replace

                if (fileUpload.HasFile)
                {

                    string ext = fileUpload.FileName.Substring(fileUpload.FileName.LastIndexOf('.') + 1);

                    //Validate
                    if (!ValidationHelper.AllowExtensionUpload(ext.ToLower().Trim()))
                    {
                        lblMessage.Text = "File không hợp lệ. Hệ thống chỉ hỗ trợ upload file xls,xlsx,edi!";
                        string msg = lblMessage.Text;
                        string prompt = "<script>$(document).ready(function(){{$.prompt('{0}!',{1});}});</script>";
                        string message = string.Format(prompt, msg, "{ prefix: 'extblue' }");
                        // registering the JavaScript on the page and controls with postback
                        this.Page.ClientScript.RegisterStartupScript(typeof(Page), "alert", message);
                        return;
                    }

                    if ((ext.ToLower().Trim() == "edi") && (DocumentType == ((int)EnumDoucmentType.Good).ToString()))
                    {
                        Guid guid = Guid.Empty;
                        try
                        {
                            EDIFileUploadClient iClient = new EDIFileUploadClient();
                            guid = iClient.UploadEDIFileData(fileUpload.FileContent);
                            iClient.Close();
                        }
                        catch (Exception ex)
                        {
                            guid = Guid.Empty;
                            lblMessage.Text = ex.Message;
                        }
                        //UploadToSharepoint upload = new UploadToSharepoint();
                        ////string site = Constant.siteUrl;
                        //SPContext ctx = SPContext.Current;
                        //// Retrieve the URL of the SharePoint site collection                        
                        //string site = ctx.Site.Url;

                        if (guid != Guid.Empty)
                        {
                            string pathFileName = string.Empty;

                            //bool IsCompleted = upload.UploadFile(fileUpload, site, guid.ToString() + ".edi", out pathFileName);
                            bool IsCompleted = true;// upload.UploadEdiFile(fileUpload, guid.ToString() + ".edi", site, "EDI_Lib", out pathFileName);
                            pathFileName = fileUpload.FileName;
                            //if (IsCompleted)
                            {
                                //Save To dB: documentid, createid, filename,pathFileName,DateAdd
                                int status;
                                if (!int.TryParse(rdnStatus.SelectedValue, out status))
                                    status = 0;
                                EdiUploadFileDto ediFile = new EdiUploadFileDto
                                {
                                    EdiId = guid,
                                    DocumentId = documentId,
                                    CreaterId = EmanifestUser.FBAUserId,
                                    CreatedDate = DateTime.Now,
                                    UploadFileName = pathFileName,
                                    Status = status,
                                };
                                EmanifestServiceClient client = null;
                                try
                                {
                                    client = new EmanifestServiceClient();
                                    ResponseDto response = client.SaveEdiFile(ediFile);
                                    if (response.IsSuccess)
                                    {
                                        //lblMessage.Text = "Upload file thành công!";
                                        EmanifestCommon.ShowMessage(this.Page, "Upload file thành công.");
                                    }
                                    else
                                    {
                                        //lblMessage.Text = response.ErroeMessage + " Error " + guid.ToString();
                                        //
                                        EmanifestCommon.ShowMessage(this.Page, "Upload file không thành công.");
                                    }
                                }
                                finally
                                {
                                    if (client != null)
                                        client.Close();
                                }
                            }
                            //else
                            //{
                            //    lblMessage.Text = "Có lỗi trong quá trình upload to sharepoint list!";
                            //}
                        }
                        else
                        {
                            //lblMessage.Text = "Có lỗi trong quá trình upload EDI file";
                            EmanifestCommon.ShowMessage(this.Page, "Upload file không thành công.");
                        }
                    }
                    else
                    {
                        var import = new ImportExcelDataClient();

                        //string fileName = string.Empty;
                        string fileName = import.UploadFileData(fileUpload.FileContent);

                        if (!string.IsNullOrEmpty(rid))
                        {
                            //Ma Ho So
                            Guid guid = new Guid(rid);

                            ResponseDto response = new ResponseDto();
                            
                            var client = new EmanifestServiceClient();
                            DocumentDto document = client.GetDocumentById(documentId);
                            client.Close();

                            bool isReplace = false;

                            if (rdnStatus.SelectedValue == "1")
                                isReplace = true;

                            bool isTemp = document.ArrivalDate == null
                                              ? false
                                              : document.ArrivalDate.CompareTo(DateTime.Now) >= 0;

                            bool isTempGood = document.ValidDays.HasValue && document.ArrivalDate.AddDays(document.ValidDays.Value).CompareTo(DateTime.Now) >= 0;


                            if (DocumentType == ((int)EnumDoucmentType.Crews).ToString())
                            {
                                response = import.ImportCrewsData(documentId, EMANIFEST.EmanifestUser.FBAUserId, EMANIFEST.EmanifestUser.FBALoginName, fileName, isTemp, isReplace);
                            }
                            else if (DocumentType == ((int)EnumDoucmentType.General).ToString())
                            {
                                response = import.ImportGeneralDeclarationData(documentId, EMANIFEST.EmanifestUser.FBAUserId, EMANIFEST.EmanifestUser.FBALoginName, fileName, isTemp, isReplace);
                            }
                            else if (DocumentType == ((int)EnumDoucmentType.Good).ToString())
                            {
                                response = import.ImportGoodDeclarationData(documentId, EMANIFEST.EmanifestUser.FBAUserId, EMANIFEST.EmanifestUser.FBALoginName, fileName, isTempGood, isReplace);
                            }
                            else if (DocumentType == ((int)EnumDoucmentType.GoodDangerous).ToString())
                            {
                                response = import.ImportDangerousGoodData(documentId, EMANIFEST.EmanifestUser.FBAUserId, EMANIFEST.EmanifestUser.FBALoginName, fileName, isTempGood, isReplace);
                            }
                            else if (DocumentType == ((int)EnumDoucmentType.Passenger).ToString())
                            {
                                response = import.ImportPassengersData(documentId, EMANIFEST.EmanifestUser.FBAUserId, EMANIFEST.EmanifestUser.FBALoginName, fileName, isTemp, isReplace);
                            }
                            else if (DocumentType == ((int)EnumDoucmentType.Stores).ToString())
                            {
                                response = import.ImportShipStoreDeclarationData(documentId, EMANIFEST.EmanifestUser.FBAUserId, EMANIFEST.EmanifestUser.FBALoginName, fileName, isTemp, isReplace);
                            }
                            else if (DocumentType == ((int)EnumDoucmentType.CrewEffect).ToString())
                            {
                                response = import.ImportCrewEffectDeclarationData(documentId, EMANIFEST.EmanifestUser.FBAUserId, EMANIFEST.EmanifestUser.FBALoginName, fileName, isTemp, isReplace);
                            }
                            else if (DocumentType == ((int)EnumDoucmentType.HouseBill).ToString())
                            {
                                response = import.ImportHouseBillData(documentId, EMANIFEST.EmanifestUser.FBAUserId, EMANIFEST.EmanifestUser.FBALoginName, fileName, isTemp, isReplace);
                            }
                            import.Close();

                            //response.IsSuccess = true;
                            if (response.IsSuccess)
                            {
                                //Response.Redirect(string.Format("{0}?id={1}", RedirectToPage.record_add, hdn.Value));
                                //lblMessage.Text = "Cập nhật hồ sơ thành công";
                                //EmanifestCommon.ShowMessage(this.Page, "Cập nhật hồ sơ thành công.");
                                
                                // Check if event is null

                                if (UploadCompleted != null)
                                {
                                    UploadEventArgs args = new UploadEventArgs(Convert.ToInt32(DocumentType));                                    
                                    UploadCompleted(args);
                                }
                                //if (btnHandler != null)
                                //    btnHandler(string.Empty);
                                //Response.Redirect(string.Format("{0}?rid={1}&&tab={2}", RedirectToPage.record_absolute, rid, DocumentType), false);
                                //this.Page.ClientScript.RegisterStartupScript(typeof(Page), "upload", @"<script>javascript:submitForm('hiddenFrame','upload');</script>");
                            }
                            else
                            {
                                //lblMessage.Text = response.ErroeMessage;
                                EmanifestCommon.ShowMessage(this.Page, "Cập nhật hồ sơ không thành công.");
                            }
                        }
                        else
                        {
                            import.Close();
                            //lblMessage.Text = "Mã hồ sơ không hợp lệ";
                            EmanifestCommon.ShowMessage(this.Page, "Mã hồ sơ không hợp lệ.");
                        }

                        //string msg = lblMessage.Text;
                        //string prompt = "<script>$(document).ready(function(){{$.prompt('{0}!',{1});}});</script>";
                        //string message = string.Format(prompt, msg, "{ prefix: 'extblue' }");
                        //// registering the JavaScript on the page and controls with postback
                        //this.Page.ClientScript.RegisterStartupScript(typeof(Page), "alert", message);
                    }
                }
                #endregion
            }
        }
    }
}
